﻿using System;
using io = System.IO;
using parser = KeyWordSearch.TreeParser;


namespace KeyWordSearch.DebugHelper
{
	public static class AstDigraphProtter
	{
		[ThreadStatic]
		private static int IdSeed;

		internal static void DrawGraph(parser::AstNode astNode, string Path)
		{
			io::StreamWriter wtr = new System.IO.StreamWriter(Path, false);

			wtr.WriteLine("digraph ast");
			wtr.WriteLine("{");
			wtr.WriteLine("\tnode [shape = record, height = 0.01, fontname=\"ＭＳ ゴシック\",fontsize=10.5];");
			IdSeed = 0;

			wtr.WriteLine("\t{0} [label=\"{{{1}}}\"];", ++IdSeed, astNode.Value.TextValue);
			DrawGraph(astNode, IdSeed, wtr);
			wtr.WriteLine("}");
			wtr.Close();
		}

		private static void DrawGraph(parser::AstNode parentNode, int parentId,io::StreamWriter wtr)
		{
			for (int i = 0; i<parentNode.Count; i++)
			{
				WriteRecord(wtr, parentNode[i], ++IdSeed, parentId);
				DrawGraph(parentNode[i], IdSeed, wtr);
			}
		}

		private static void WriteRecord(io::StreamWriter wtr,parser::AstNode node, int Id,int ParentId)
		{
			string text = node.Value.TextValue;

			switch (node.Value.Attribute)
			{
				case KeyWordSearch.TreeParser.TokenType.OperatorOR:
					text = "\\|";
					break;

				case KeyWordSearch.TreeParser.TokenType.OperatorShortCutedOR:
					text = "\\|\\|";
					break;

				case KeyWordSearch.TreeParser.TokenType.StringLiteral:
					text = text.Trim('\"');
					break;
			}

			
			wtr.WriteLine("\t{0} [label=\"{{{1}|{2}}}\"];", Id,text,node.Value.Attribute);
			if (ParentId != -1)
			{
				wtr.WriteLine("\t{0} -> {1};", ParentId, Id);
			}
		}
	}
}
